package com.sq.shortlink.project.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sq.shortlink.project.dao.entity.LinkNetWorkStatsDO;
import com.sq.shortlink.project.dto.req.ShortLinkStatsReqDTO;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 访问监控网络持久层
 * @author quan
 */
@Mapper
public interface LinkNetWorkStatsMapper extends BaseMapper<LinkNetWorkStatsDO> {
    /**
     * 记录访问设备数据
     */
    @Insert("INSERT INTO t_link_network_stats (full_short_url,gid,date,cnt,network,create_time,update_time,del_flag)\n" +
            "VALUES(#{linkNetWorkStats.fullShortUrl},#{linkNetWorkStats.gid},#{linkNetWorkStats.date},#{linkNetWorkStats.cnt},#{linkNetWorkStats.network},NOW(),NOW(),0) ON DUPLICATE KEY\n" +
            "UPDATE\n" +
            "  cnt = cnt + #{linkNetWorkStats.cnt}")
    void shortLinkNetWorkStats(@Param("linkNetWorkStats") LinkNetWorkStatsDO linkNetWorkStatsDO);

    /**
     * 根据短链接获取指定日期内访问网络监控数据
     */
    @Select("SELECT " +
            "    network, " +
            "    SUM(cnt) AS cnt " +
            "FROM " +
            "    t_link_network_stats " +
            "WHERE " +
            "    full_short_url = #{param.fullShortUrl} " +
            "    AND gid = #{param.gid} " +
            "    AND date BETWEEN #{param.startDate} and #{param.endDate} " +
            "GROUP BY " +
            "    full_short_url, gid, network;")
    List<LinkNetWorkStatsDO> listNetworkStatsByShortLink(@Param("param") ShortLinkStatsReqDTO requestParam);
}
